package postgres

import (
	"context"
	"github.com/jackc/pgx/v5"
	"log"
	"ozonTest/internal/domain/posts/dao"
	"ozonTest/internal/domain/posts/model"
	"sync"
)

type postDAO struct {
	conn *pgx.Conn
	m    sync.RWMutex
}

func NewPostsRepo(conn *pgx.Conn) dao.PostDAO {
	return &postDAO{conn: conn}
}

func (p *postDAO) CreatePost(post *model.Post) error {
	query := `INSERT INTO posts (title, content, comments_enabled) VALUES ($1, $2, $3) RETURNING id, created_at`
	err := p.conn.QueryRow(context.Background(), query, post.Title, post.Content, post.CommentsEnabled).Scan(&post.ID, &post.CreatedAt)
	if err != nil {
		log.Printf("Error creating post: %v", err)
		return err
	}
	log.Printf("Post created: %+v", post)
	return nil
}

func (p *postDAO) GetPost(id int) (*model.Post, error) {
	post := &model.Post{}
	query := `SELECT id, title, content, comments_enabled, created_at FROM posts WHERE id = $1`
	err := p.conn.QueryRow(context.Background(), query, id).Scan(&post.ID, &post.Title, &post.Content, &post.CommentsEnabled, &post.CreatedAt)
	if err != nil {
		log.Printf("Error getting post by ID %d: %v", id, err)
		return nil, err
	}
	log.Printf("Post retrieved: %+v", post)
	return post, nil
}

func (p *postDAO) GetAllPosts() ([]model.Post, error) {
	var posts []model.Post
	query := `SELECT id, title, content, comments_enabled, created_at FROM posts`
	rows, err := p.conn.Query(context.Background(), query)
	if err != nil {
		log.Printf("Error getting all posts: %v", err)
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		var post model.Post
		err := rows.Scan(&post.ID, &post.Title, &post.Content, &post.CommentsEnabled, &post.CreatedAt)
		if err != nil {
			log.Printf("Error scanning row: %v", err)
			return nil, err
		}
		posts = append(posts, post)
	}
	log.Printf("All posts retrieved: %+v", posts)
	return posts, nil
}

func (p *postDAO) DeletePost(id int) error {
	query := `DELETE FROM posts WHERE id = $1`
	_, err := p.conn.Exec(context.Background(), query, id)
	if err != nil {
		log.Printf("Error deleting post by ID %d: %v", id, err)
		return err
	}
	log.Printf("Post deleted: ID %d", id)
	return nil
}

func (p *postDAO) ChangeCommentsAllowed(postUUID int, commentsAllowed bool) error {
	query := `UPDATE posts SET comments_enabled = $1 WHERE id = $2`
	_, err := p.conn.Exec(context.Background(), query, commentsAllowed, postUUID)
	if err != nil {
		log.Printf("Error changing comments allowed for post ID %d: %v", postUUID, err)
		return err
	}
	log.Printf("Comments allowed changed for post ID %d: %v", postUUID, commentsAllowed)
	return nil
}
